//
//  ViewController.m
//  知乎日报
//
//  Created by 陈明光 on 2019/9/4.
//  Copyright © 2019 陈明光. All rights reserved.
//

#import "HomeViewController.h"

#import "DetailViewController.h"
#import "HomeTableViewCell.h"
#import "LatestModel.h"
#import "StroriesModel.h"
#import "PicturesView.h"
#define CELLID @"HomeCell"

@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableView;
//设置数据源
@property(nonatomic,strong)NSMutableArray *datas;
@property(nonatomic,strong)PicturesView *picturesView;
@property(nonatomic,strong)LatestModel *latestModel;
//导航栏
@property(nonatomic,strong)UIView *headerView;
//导航栏标题和按钮
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UIButton *leftBtn;
@end

@implementation HomeViewController

#pragma mark 懒加载
-(UILabel *)titleLabel{
    if (!_titleLabel) {
        UILabel *label=[UILabel new];
        //设置标题样式,字体颜色
        label.attributedText=[[NSAttributedString alloc]initWithString:@"今日要闻" attributes:@{
                                                                                NSFontAttributeName:[UIFont systemFontOfSize:18]
                                                                                ,NSForegroundColorAttributeName:[UIColor whiteColor]
                                                                                            
                                                                                            }];
        [label sizeToFit];
        label.textAlignment=NSTextAlignmentCenter;
        _titleLabel=label;
    }
    return _titleLabel;
}
-(UIButton *)leftBtn{
    if (!_leftBtn) {
         _leftBtn=[[UIButton alloc]init];
        [_leftBtn addTarget:self action:@selector(didLeftMenubutton:) forControlEvents:UIControlEventTouchUpInside];
        [_leftBtn setImage:[UIImage imageNamed:@"Home_Icon"] forState:UIControlStateNormal];
        
    }
    return _leftBtn;
    
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height)];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        //去掉cell下面那条线
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        //设置cell
        [_tableView registerClass:[HomeTableViewCell class] forCellReuseIdentifier:CELLID];
        
        //添加监听
        [_tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
        //添加一个轮播图的View
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
        _tableView.tableHeaderView=view;
        
    }
    return _tableView;
}

//添加导航栏
-(UIView *)headerView{
    if (!_headerView) {
        _headerView=[UIView new];
        //导航栏颜色
        _headerView.backgroundColor=[UIColor colorWithRed:23/225.0 green:150/255.0 blue:210/225.0 alpha:0];
        _headerView.frame=CGRectMake(0, 0, SCREEN_WIDTH, 56);
        //将导航栏标题和按钮添加到导航栏上
        [_headerView addSubview:self.leftBtn];
        [_headerView addSubview:self.titleLabel];
        //设置位置
        self.titleLabel.sd_layout.centerYEqualToView(_headerView).centerXEqualToView(_headerView).widthIs(150).heightIs(30);
        
        self.leftBtn.sd_layout.topSpaceToView(_headerView, 13).leftSpaceToView(_headerView, 12).widthIs(30).heightIs(30);
       
    }
    return _headerView;
}

-(PicturesView *)picturesView{
    if (!_picturesView) {
        _picturesView=[[PicturesView alloc]init];
        _picturesView.frame=CGRectMake(0, 0, SCREEN_WIDTH, 240);
    }
    return _picturesView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.picturesView];
    //添加到主视图*****注意这个要添加到最后，不然会被覆盖下去
    [self.view addSubview:self.headerView];
//    self.picturesView.sd_layout.topSpaceToView(self.view, 0).leftSpaceToView(self.view, 0).rightSpaceToView(self.view, 0).heightIs(220);
    
    [self getLatest];
}
#pragma mark - 获取网络新闻数据
-(void)getLatest{
    //iOS9 以后使用https
    [[AFHTTPSessionManager manager]GET:@"https://news-at.zhihu.com/api/4/news/latest" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [LatestModel mj_setupObjectClassInArray:^NSDictionary *{
            return @{
                     @"stories":@"StroriesModel",
                     @"top_stories":@"PicturesModel"
                     };
        }];
        //通过字典来创建模型
        LatestModel *model=[LatestModel mj_objectWithKeyValues:responseObject];
        self.datas=model.stories.mutableCopy;
        self.latestModel=model;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark - UITableView Delegate & DataSource
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        return [self.tableView cellHeightForIndexPath:indexPath model:self.datas[indexPath.row] keyPath:@"model" cellClass:[HomeTableViewCell class] contentViewWidth:self.view.frame.size.width];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datas.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CELLID];
    cell.model=self.datas[indexPath.row];
    return cell;
}
//用户点击cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailViewController *detaiVC=[[DetailViewController alloc]init];
    detaiVC.stroriesModel=self.datas[indexPath.row];
    [self.navigationController pushViewController:detaiVC animated:YES];
}
//上面设置的监听就会调用这个方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    //判断一下是否为什么那个监听的名字
    if ([keyPath isEqualToString:@"contentOffset"]) {
        //拿到y轴
        CGFloat yOffset=self.tableView.contentOffset.y;
        //如果y轴x小于等于0，改变轮播图的高度和y轴的坐标
        if (yOffset<=0) {
            self.picturesView.height=220-yOffset;
            CGRect frame=self.picturesView.frame;
            frame.origin.y=0;
            self.picturesView.frame=frame;
        }else{
            CGRect frame=self.picturesView.frame;
            frame.origin.y=0-yOffset;
            self.picturesView.frame=frame;
        }
        //设置一个初始的透明值
        CGFloat alpha=0;
        //如果y轴的坐标小于100，则透明度为0
        if (yOffset<100) {
            alpha=0;
        ////如果y轴的坐标小于100，则透明度为(yOffset-100)/(165-100)
        }else if (yOffset<165){
            alpha=(yOffset-100)/(165-100);
        }else{
            alpha=1;
        }
        
        _headerView.backgroundColor=[UIColor colorWithRed:23/225.0 green:150/255.0 blue:210/225.0 alpha:alpha];
    }
}

//通知tabkeView获取数据源
-(void)setDatas:(NSMutableArray *)datas{
    _datas=datas;
    
    [self.tableView reloadData];
}
-(void)setLatestModel:(LatestModel *)latestModel{
    _latestModel=latestModel;
    self.picturesView.images=latestModel.top_stories;
}
-(void)didLeftMenubutton:(UIButton *)btn{
    
}
@end
